using System.Collections.Generic;
using UnityEngine;

namespace ProceduralPrimitivesUtil
{
	public class PPCombiner : PPBase
	{
		public List<GameObject> elements = new List<GameObject>();

		public bool includeChildren;

		public bool applyTargetsTransform = true;

		private List<Mesh> mList;

		protected override void CreateMesh()
		{
			m_mesh.name = "Combined Mesh";
			mList = new List<Mesh>();
			foreach (GameObject element in elements)
			{
				if (element == base.gameObject)
				{
					continue;
				}
				if (includeChildren)
				{
					MeshFilter[] componentsInChildren = element.GetComponentsInChildren<MeshFilter>();
					foreach (MeshFilter meshFilter in componentsInChildren)
					{
						if (!(meshFilter.sharedMesh == null))
						{
							if (applyTargetsTransform)
							{
								AddMesh(meshFilter.sharedMesh, meshFilter.transform);
							}
							else
							{
								AddMesh(meshFilter.sharedMesh);
							}
						}
					}
				}
				else
				{
					MeshFilter component = element.GetComponent<MeshFilter>();
					if (!(component == null) && !(component.sharedMesh == null))
					{
						AddMesh(component.sharedMesh);
					}
				}
			}
			mList = null;
		}

		private void AddMesh(Mesh m, Transform trans = null)
		{
			if (mList.Contains(m))
			{
				return;
			}
			mList.Add(m);
			Vector3[] vertices = m.vertices;
			Vector3[] normals = m.normals;
			int[] triangles = m.triangles;
			if (m_rotation != Quaternion.identity)
			{
				for (int i = 0; i < vertices.Length; i++)
				{
					vertices[i] = m_rotation * vertices[i];
				}
				for (int j = 0; j < normals.Length; j++)
				{
					normals[j] = m_rotation * normals[j];
				}
			}
			if (pivotOffset != Vector3.zero)
			{
				for (int k = 0; k < vertices.Length; k++)
				{
					vertices[k] += pivotOffset;
				}
			}
			if (trans != null)
			{
				for (int l = 0; l < vertices.Length; l++)
				{
					vertices[l] = trans.TransformVector(vertices[l]) + trans.localPosition;
				}
				for (int n = 0; n < normals.Length; n++)
				{
					normals[n] = trans.worldToLocalMatrix.transpose * normals[n];
				}
			}
			for (int num = 0; num < triangles.Length; num++)
			{
				triangles[num] += m_vertices.Count;
			}
			m_vertices.AddRange(vertices);
			m_normals.AddRange(normals);
			m_triangles.AddRange(triangles);
			m_uv.AddRange(m.uv);
		}
	}
}
